<template>
  <div class="video-map-container">
    <!-- 左侧摄像头树形视图 -->
    <div class="left-panel">
      <CameraTreeView 
        :show-header="true"
        :use-store-data="true"
        :show-drag-tip="false"
        :enable-drag="false"
        :show-checkboxes="false"
        @node-click="handleCameraNodeClick"
        @control-ptz="handlePTZControl"
        @refresh="handleRefreshTree"
      />
    </div>

    <!-- 右侧地图视图 -->
    <div class="right-panel" :class="{ 'fullscreen-mode': isFullscreen }">
      <div class="electronic-map-view">
        <div id="cesiumContainer" class="cesium-container"></div>

        <!-- 全屏按钮 -->
        <div class="fullscreen-controls">
          <button
            @click="toggleFullscreen"
            class="fullscreen-btn"
            :title="isFullscreen ? '退出全屏' : '全屏显示'"
          >
            <svg v-if="!isFullscreen" class="fullscreen-icon" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
              <path d="M7 14H5V19H10V17H7V14Z" fill="currentColor"/>
              <path d="M5 10H7V7H10V5H5V10Z" fill="currentColor"/>
              <path d="M17 14H19V19H14V17H17V14Z" fill="currentColor"/>
              <path d="M14 5V7H17V10H19V5H14Z" fill="currentColor"/>
            </svg>
            <svg v-else class="fullscreen-icon" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
              <path d="M9 9H11V7H7V11H9V9Z" fill="currentColor"/>
              <path d="M15 9H17V7H13V11H15V9Z" fill="currentColor"/>
              <path d="M9 15H11V13H7V17H9V15Z" fill="currentColor"/>
              <path d="M15 15H17V13H13V17H15V15Z" fill="currentColor"/>
            </svg>
          </button>
        </div>

        <!-- 地图位置信息对话框 -->
        <MapLocationDialog
          :visible="dialogVisible"
          :title="selectedLocation?.name"
          :selected-location="selectedLocation"
          :is-editing="isEditing"
          @close="onDialogClose"
          @update:visible="dialogVisible = $event"
        />

        <!-- Marker Tooltip -->
        <div 
          v-if="tooltipVisible" 
          class="marker-tooltip"
          :style="{ left: tooltipPosition.x + 'px', top: tooltipPosition.y + 'px' }"
        >
          <div class="tooltip-content">
            <div class="tooltip-item">
              <span class="tooltip-label">流媒体:</span>
              <span class="tooltip-value">{{ tooltipData.nvrName }}</span>
            </div>
            <div class="tooltip-item">
              <span class="tooltip-label">名称:</span>
              <span class="tooltip-value">{{ tooltipData.name }}</span>
            </div>
            <div class="tooltip-item">
              <span class="tooltip-label">IP:</span>
              <span class="tooltip-value">{{ tooltipData.ip }}</span>
            </div>
            <div class="tooltip-item">
              <span class="tooltip-label">经度:</span>
              <span class="tooltip-value">{{ tooltipData.lng.toFixed(6) }}</span>
            </div>
            <div class="tooltip-item">
              <span class="tooltip-label">纬度:</span>
              <span class="tooltip-value">{{ tooltipData.lat.toFixed(6) }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, nextTick, onMounted, onUnmounted, watch } from 'vue';
import CameraTreeView from '@/components/CameraTreeView.vue';
import MapLocationDialog from '@/components/MapLocationDialog.vue';
import { useCameraStore } from '@/stores/camera';
import * as Cesium from 'cesium';
import { warning } from '@/utils/toast';
import { createAmapProvider, createOSMProvider } from '@/config/mapProviders';

// 定义CameraTreeNode接口
interface CameraTreeNode {
  id: string
  name: string
  type: 'folder' | 'camera'
  status?: 'online' | 'offline'
  ip?: string
  url?: string
  children?: CameraTreeNode[]
  parentId?: string | number
  hasMapMarker?: boolean
}

// Store
const cameraStore = useCameraStore();

// Cesium viewer 实例
let viewer: Cesium.Viewer | null = null;
const entities: Cesium.Entity[] = [];

// 摄像头数据 - 现在使用真实的 allDeviceInMap 数据
const mockData = ref<any[]>([]);

const dialogVisible = ref(false);
const selectedLocation = ref<any>(null);
const isEditing = ref(false);
const isFullscreen = ref(false);
const tooltipVisible = ref(false);
const tooltipPosition = ref({ x: 0, y: 0 });
const tooltipData = ref({ name: '', ip: '', lng: 0, lat: 0, nvrName: '' });

// 在线摄像头图标 - 使用device_online.svg
const cameraIconOnline = ref(`data:image/svg+xml;charset=utf-8,${encodeURIComponent(`
<svg t="1759203581614" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="8673" xmlns:xlink="http://www.w3.org/1999/xlink" width="32" height="32">
  <path d="M601.043478 979.478261c0 24.598261-39.846957 44.521739-89.043478 44.521739s-89.043478-19.923478-89.043478-44.521739 39.846957-44.521739 89.043478-44.521739 89.043478 19.923478 89.043478 44.521739z" fill="#44C00A" fill-opacity=".2" p-id="8674"></path>
  <path d="M556.521739 979.478261c0 12.288-19.923478 22.26087-44.521739 22.260869s-44.521739-9.97287-44.521739-22.260869 19.923478-22.26087 44.521739-22.26087 44.521739 9.97287 44.521739 22.26087zM890.434783 382.753391C890.434783 594.098087 623.304348 756.869565 512 912.695652 400.695652 756.869565 133.565217 594.142609 133.565217 382.753391S302.992696 0 512 0s378.434783 171.364174 378.434783 382.753391z" fill="#44C00A" p-id="8675"></path>
  <path d="M777.037913 384.734609L408.33113 134.233043C407.596522 133.565217 406.928696 133.565217 406.238609 133.565217h-39.891479a3.85113 3.85113 0 0 0-3.494956 2.092522l-57.366261 93.050435c-0.712348 0.712348-0.712348 1.402435-0.712348 2.114783v29.384347c0 1.402435 0.712348 2.782609 2.114783 3.494957l326.032695 205.690435c0.667826 0.690087 1.380174 0.690087 2.092522 0.690087h25.177044c0.712348 0 1.402435 0 2.114782-0.690087l114.732522-77.668174c2.80487-2.092522 2.80487-5.587478 0-6.989913zM340.457739 452.563478v-60.861217c0-2.092522-1.402435-3.494957-3.494956-4.185044l-42.674087-8.392347c-2.80487-0.712348-4.897391 0.667826-4.897392 3.494956v211.277913c0 2.80487 2.80487 4.897391 5.587479 4.207304l42.696347-15.404521a4.719304 4.719304 0 0 0 2.782609-4.185044v-69.965913c0-2.092522 2.114783-4.207304 4.207304-4.207304h76.26574a5.342609 5.342609 0 0 0 3.494956-1.402435l41.271652-58.056348c1.402435-2.114783 0.690087-4.897391-1.402434-5.609739l-50.376348-27.981913c-2.092522-1.402435-4.897391 0-5.587479 2.114783l-13.289739 41.271652a4.719304 4.719304 0 0 1-4.207304 2.804869H346.067478c-3.494957 0-5.609739-2.114783-5.609739-4.897391zM308.313043 325.965913l23.79687-27.291826c1.402435-1.402435 3.494957-1.402435 5.587478-0.690087l278.461218 193.090783h0.690087c9.794783 4.897391 19.589565 10.48487 28.694261 16.784695a5.988174 5.988174 0 0 0 4.897391 0c2.515478-1.958957 7.212522-5.520696 12.532869-9.572174 7.92487-6.010435 17.296696-13.111652 23.151305-17.719652 2.092522-1.380174 4.897391 0.712348 4.185043 2.80487l-12.599652 39.891478c0 0.289391 0 0.445217-0.044522 0.601043-0.066783 0.222609-0.222609 0.378435-0.645565 0.779131l-13.979826 14.692174c-0.712348 0.712348-1.402435 1.402435-2.80487 1.402435h-27.291826c-0.690087 0-1.402435 0-2.092521-0.690087L308.98087 332.265739c-2.114783-1.402435-2.114783-4.117787-0.712348-6.299826z" fill="#FFFFFF" p-id="8676"></path>
</svg>
`)}`);
// 离线摄像头图标 - 使用内联SVG
const cameraIconOffline = ref(`data:image/svg+xml;charset=utf-8,${encodeURIComponent(`
<svg viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" width="32" height="32">
  <path d="M424.851064 980.425532a87.148936 43.574468 0 1 0 174.297872 0 87.148936 43.574468 0 1 0-174.297872 0Z" fill="#606060" fill-opacity=".2"></path>
  <path d="M468.425532 980.425532a43.574468 21.787234 0 1 0 87.148936 0 43.574468 21.787234 0 1 0-87.148936 0Z" fill="#606060"></path>
  <path d="M882.382979 374.609702C882.382979 581.457702 620.93617 740.765957 512 893.276596 403.06383 740.765957 141.617021 581.501277 141.617021 374.609702S307.43966 0 512 0s370.382979 167.718128 370.382979 374.609702z" fill="#606060"></path>
  <path d="M771.398809 376.548766L410.536851 131.377021C409.817872 130.723404 409.164255 130.723404 408.488851 130.723404h-39.042723a3.769191 3.769191 0 0 0-3.420596 2.048l-56.145702 91.070639c-0.697191 0.697191-0.697191 1.372596-0.697192 2.069787v28.759149c0 1.372596 0.697191 2.723404 2.069788 3.420595l319.095829 201.314043c0.653617 0.675404 1.350809 0.675404 2.048 0.675404h24.641362c0.697191 0 1.372596 0 2.069787-0.675404l112.291405-76.01566c2.745191-2.048 2.745191-5.468596 0-6.841191zM344.107574 442.934468v-59.566298c0-2.048-1.372596-3.420596-3.420595-4.096l-41.766128-8.213787c-2.745191-0.697191-4.793191 0.653617-4.793191 3.420596v206.782638c0 2.745191 2.745191 4.793191 5.468595 4.117787l41.787915-15.076766a4.618894 4.618894 0 0 0 2.723404-4.096v-68.477276c0-2.048 2.069787-4.117787 4.117788-4.117788h74.643064a5.228936 5.228936 0 0 0 3.420595-1.372595l40.393532-56.821107c1.372596-2.069787 0.675404-4.793191-1.372596-5.490383l-49.30451-27.386553c-2.048-1.372596-4.793191 0-5.468596 2.069787l-13.006979 40.393532a4.618894 4.618894 0 0 1-4.117787 2.745192H349.597957c-3.420596 0-5.490383-2.069787-5.490383-4.793192zM312.646809 319.030468l23.290553-26.711149c1.372596-1.372596 3.420596-1.372596 5.468595-0.675404l272.536511 188.982468h0.675404c9.586383 4.793191 19.172766 10.261787 28.083745 16.427574a5.860766 5.860766 0 0 0 4.793192 0c2.461957-1.917277 7.059064-5.403234 12.266212-9.36851 7.756255-5.882553 16.928681-12.832681 22.658724-17.342638 2.048-1.350809 4.793191 0.697191 4.096 2.745191l-12.331575 39.042723c0 0.283234 0 0.435745-0.043574 0.588256-0.065362 0.217872-0.217872 0.370383-0.63183 0.762553l-13.682383 14.379574c-0.697191 0.697191-1.372596 1.372596-2.745192 1.372596h-26.711148c-0.675404 0-1.372596 0-2.048-0.675404L313.300426 325.196255c-2.069787-1.372596-2.069787-4.117787-0.697192-6.165787z" fill="#FFFFFF"></path>
</svg>
`)}`);

// 从cameraStore获取摄像头数据并转换为地图点位格式
const loadCamerasToMap = async () => {
  try {
    // 如果 allDeviceInMap 为空，调用 fetchCameraTree 来获取数据
    if (cameraStore.allDeviceInMap.length === 0) {
      await cameraStore.fetchCameraTree();
    }
    
    // 使用 allDeviceInMap 作为数据源
    const mapDevices = cameraStore.allDeviceInMap;
    
    // 获取所有设备的状态信息（从树形结构中）
    const getAllDevicesWithStatus = (nodes: any[]): any[] => {
      let devices: any[] = [];
      nodes.forEach(node => {
        if (node.devices && node.devices.length > 0) {
          devices = devices.concat(node.devices);
        }
        if (node.children) {
          devices = devices.concat(getAllDevicesWithStatus(node.children));
        }
      });
      return devices;
    };
    // 转换为地图点位格式，合并状态信息
    const mapPoints = mapDevices.map(device => {
      return {
        id: device.id,
        name: device.name,
        nvrName: cameraStore.getFlvServerListByNvrId(device.nvrId).name,
        nvrId: device.nvrId,
        ip: device.ip,
        position: { 
          lng: parseFloat(String(device.longitude)) || 118.175393, 
          lat: parseFloat(String(device.latitude)) || 39.635113, 
          height: 2000 
        },
        flvUrl: device.flv || device.flvsub,
        status: device.status
      };
    });
    
    // 只使用真实数据
    mockData.value = mapPoints;
    
    // 如果 viewer 已经初始化，刷新实体
    if (viewer) {
      addCameraEntities();
    }
    
    console.log(`已加载 ${mapPoints.length} 个设备到地图`);
  } catch (error) {
    console.error('加载设备数据到地图失败:', error);
    mockData.value = [];
    if (viewer) {
      addCameraEntities();
    }
  }
};

// 注意：getAllDevicesFromTree 函数已不再需要，因为我们直接使用 allDeviceInMap

// 处理摄像头节点点击
const handleCameraNodeClick = async (node: CameraTreeNode) => {
  if (node.type === 'camera') {
    // 查找对应的地图点位
    const mapPoint = mockData.value.find(point => 
      point.name === node.name || String(point.id) === String(node.id)
    );
    
    if (mapPoint && viewer) {
      // 飞行到该摄像头位置 - 道路地图使用较低高度
      viewer.camera.flyTo({
        destination: Cesium.Cartesian3.fromDegrees(
          mapPoint.position.lng,
          mapPoint.position.lat,
          1500 // 道路地图使用较低高度以便更好地观察道路
        ),
        duration: 2.0
      });
      console.log(`已飞行到摄像头: ${node.name} (${mapPoint.position.lng}, ${mapPoint.position.lat})`);
      
      // 弹出设备详情对话框
      selectedLocation.value = mapPoint;
      dialogVisible.value = true;
      isEditing.value = false;
    } else {
      // 摄像头未在地图中标记，显示提示
      warning(`摄像头 ${node.name} 暂未在地图中标记`);
      console.warn(`摄像头 ${node.name} 暂未在地图中标记`);
    }
  }
};

// 处理云台控制
const handlePTZControl = (camera: CameraTreeNode) => {
  console.log('云台控制:', camera);
};

// 处理刷新树形数据
const handleRefreshTree = async () => {
  try {
    await cameraStore.fetchCameraTree();
    await loadCamerasToMap();
    if (viewer) {
      flyToAllCameras();
    }
  } catch (error) {
    console.error('刷新数据失败:', error);
  }
};

// 切换全屏模式
const toggleFullscreen = () => {
  isFullscreen.value = !isFullscreen.value;
  
  // 延迟调整 Cesium viewer 大小
  nextTick(() => {
    if (viewer) {
      viewer.resize();
    }
  });
};

// 页面挂载时初始化
onMounted(async () => {
  await loadCamerasToMap();
  // 等待DOM渲染完成后初始化Cesium
  nextTick(async () => {
    await initializeCesium();
  });
});

// 页面卸载时清理资源
onUnmounted(() => {
  if (viewer) {
    viewer.destroy();
    viewer = null;
  }
});

// 初始化 Cesium viewer
const initializeCesium = async () => {
  // 设置 Cesium Token - 从环境变量读取
  Cesium.Ion.defaultAccessToken = import.meta.env.VITE_CESIUM_ION_TOKEN
  
  // 创建 viewer
  viewer = new Cesium.Viewer('cesiumContainer', {
    sceneMode: Cesium.SceneMode.SCENE3D,
    sceneModePicker: false,
    baseLayerPicker: false,
    geocoder: false,
    homeButton: false,
    infoBox: false,
    navigationHelpButton: false,
    animation: false,
    timeline: false,
    fullscreenButton: false,
    vrButton: false
  });
  
  // 移除默认的卫星地图，添加高德地图服务
  viewer.imageryLayers.removeAll();
  
  // 优先使用高德地图
  try {
    const amapProvider = createAmapProvider();
    viewer.imageryLayers.addImageryProvider(amapProvider);
    console.log('已加载高德地图服务');
  } catch (error) {
    console.warn('高德地图加载失败，尝试OpenStreetMap:', error);
    
    // 备用方案：使用OpenStreetMap
    try {
      const osmProvider = createOSMProvider();
      viewer.imageryLayers.addImageryProvider(osmProvider);
      console.log('已加载OpenStreetMap服务');
    } catch (osmError) {
      console.error('OpenStreetMap也加载失败:', osmError);
    }
  }
  
  // 保存到全局变量供其他方法使用
  (window as any).cesiumViewer = viewer;
  
  // 优化地图显示设置
  viewer.scene.globe.enableLighting = false; // 关闭光照，让道路更清晰
  viewer.scene.globe.showGroundAtmosphere = false; // 关闭大气效果
  viewer.scene.fog.enabled = false; // 关闭雾效
  
  // 设置相机控制，让地图更适合查看道路
  viewer.scene.screenSpaceCameraController.enableTilt = true; // 允许倾斜
  viewer.scene.screenSpaceCameraController.enableRotate = true; // 允许旋转
  viewer.scene.screenSpaceCameraController.enableZoom = true; // 允许缩放
  viewer.scene.screenSpaceCameraController.minimumZoomDistance = 100; // 设置最小缩放距离
  
  // 添加摄像头实体
  addCameraEntities();
  
  // 设置初始视角 - 飞行到所有摄像头的合适视角
  flyToAllCameras();
  
  // 添加点击事件监听
  viewer.cesiumWidget.screenSpaceEventHandler.setInputAction((event: any) => {
    const pickedObject = viewer!.scene.pick(event.position);
    if (Cesium.defined(pickedObject) && Cesium.defined(pickedObject.id)) {
      const entity = pickedObject.id;
      if ((entity as any).cameraData) {
        const cameraData = (entity as any).cameraData;
        onEntityClick(cameraData);
      }
    }
  }, Cesium.ScreenSpaceEventType.LEFT_CLICK);

  // 添加鼠标移动事件监听 - 用于tooltip
  viewer.cesiumWidget.screenSpaceEventHandler.setInputAction((event: any) => {
    const pickedObject = viewer!.scene.pick(event.endPosition);
    if (Cesium.defined(pickedObject) && Cesium.defined(pickedObject.id)) {
      const entity = pickedObject.id;
      if ((entity as any).cameraData) {
        const cameraData = (entity as any).cameraData;
        showTooltip(event.endPosition, cameraData);
      }
    } else {
      hideTooltip();
    }
  }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
  
  console.log('Cesium viewer 初始化完成');
};

// 添加摄像头实体到地图
const addCameraEntities = () => {
  if (!viewer) return;
  
  // 清除现有实体
  entities.forEach(entity => {
    viewer!.entities.remove(entity);
  });
  entities.length = 0;
  
  // 添加摄像头实体
  mockData.value.forEach(item => {
    // 根据状态选择图标
    const iconUrl = item.status === 1 ? cameraIconOnline.value : cameraIconOffline.value;
    const entity = viewer!.entities.add({
      id: `camera_${item.id}`,
      position: Cesium.Cartesian3.fromDegrees(
        item.position.lng, 
        item.position.lat, 
        item.position.height
      ),
      billboard: {
        image: iconUrl,
        scale: 1.0,
        show: true,
        disableDepthTestDistance: Number.POSITIVE_INFINITY,
        heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
        verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
        horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
        eyeOffset: new Cesium.Cartesian3(0, 0, 0)
      },
      label: {
        text: item.name,
        font: '14px sans-serif',
        pixelOffset: new Cesium.Cartesian2(0, -35),
        show: true,
        disableDepthTestDistance: Number.POSITIVE_INFINITY,
        fillColor: Cesium.Color.WHITE,
        outlineColor: Cesium.Color.BLACK,
        outlineWidth: 2,
        style: Cesium.LabelStyle.FILL_AND_OUTLINE,
        verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
        horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
        eyeOffset: new Cesium.Cartesian3(0, 0, 0),
        scaleByDistance: new Cesium.NearFarScalar(100, 1.0, 10000, 0.8),
        translucencyByDistance: new Cesium.NearFarScalar(100, 1.0, 10000, 0.5),
        heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
        distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0, 50000)
      }
    });
    
    // 将摄像头数据存储为实体的自定义属性
    (entity as any).cameraData = item;
    
    entities.push(entity);
  });
  
  console.log(`已添加 ${mockData.value.length} 个摄像头实体到地图`);
};

// 飞行到所有摄像头的合适视角
const flyToAllCameras = () => {
  if (!viewer) return;
  
  // 如果没有设备数据，飞行到默认位置 - 道路地图使用较低高度
  if (mockData.value.length === 0) {
    viewer.camera.flyTo({
      destination: Cesium.Cartesian3.fromDegrees(118.090622, 39.223579, 3000),
      duration: 2.0
    });
    console.log('没有设备数据，飞行到默认位置: 118.090622, 39.223579');
    return;
  }
  
  try {
    // 如果只有一个摄像头，直接飞到该位置 - 道路地图使用较低高度
    if (mockData.value.length === 1) {
      const camera = mockData.value[0];
      viewer.camera.flyTo({
        destination: Cesium.Cartesian3.fromDegrees(
          camera.position.lng, 
          camera.position.lat, 
          2000
        ),
        duration: 2.0
      });
      return;
    }
    
    // 计算所有摄像头的边界
    let minLng = Infinity, maxLng = -Infinity;
    let minLat = Infinity, maxLat = -Infinity;
    
    mockData.value.forEach(camera => {
      minLng = Math.min(minLng, camera.position.lng);
      maxLng = Math.max(maxLng, camera.position.lng);
      minLat = Math.min(minLat, camera.position.lat);
      maxLat = Math.max(maxLat, camera.position.lat);
    });
    
    // 计算中心点和合适的高度
    const centerLng = (minLng + maxLng) / 2;
    const centerLat = (minLat + maxLat) / 2;
    
    // 根据边界范围计算合适的高度
    const lngRange = maxLng - minLng;
    const latRange = maxLat - minLat;
    const maxRange = Math.max(lngRange, latRange);
    
    // 计算合适的高度（根据范围调整）- 道路地图使用较低高度
    let height = 5000; // 默认高度，道路地图降低
    if (maxRange > 0) {
      height = Math.max(2000, maxRange * 80000); // 根据范围动态调整高度，道路地图降低
    }
    
    // 飞行到计算出的位置
    viewer.camera.flyTo({
      destination: Cesium.Cartesian3.fromDegrees(centerLng, centerLat, height),
      duration: 3.0
    });
    
    console.log(`飞行到摄像头区域中心: ${centerLng.toFixed(6)}, ${centerLat.toFixed(6)}, 高度: ${height}`);
  } catch (error) {
    console.error('飞行到摄像头位置失败:', error);
    // 如果计算失败，使用默认位置 - 道路地图使用较低高度
    viewer.camera.flyTo({
      destination: Cesium.Cartesian3.fromDegrees(118.090622, 39.223579, 5000),
      duration: 2.0
    });
  }
};

const onEntityClick = (item: any) => {
  selectedLocation.value = item;
  dialogVisible.value = true;
  isEditing.value = false;
};

// 显示tooltip
const showTooltip = (position: any, cameraData: any) => {
  console.log('showTooltip', position, cameraData);
  tooltipData.value = {
    name: cameraData.name,
    ip: cameraData.ip || '未知IP',
    lng: cameraData.position.lng,
    lat: cameraData.position.lat,
    nvrName: cameraData.nvrName
  };
  
  // 将Cesium屏幕坐标转换为DOM坐标
  const canvas = viewer!.canvas;
  const rect = canvas.getBoundingClientRect();
  tooltipPosition.value = {
    x: position.x + rect.left + 10, // 偏移10px避免鼠标遮挡
    y: position.y + rect.top - 10
  };
  
  tooltipVisible.value = true;
};

// 隐藏tooltip
const hideTooltip = () => {
  tooltipVisible.value = false;
};

const onDialogClose = () => {
  selectedLocation.value = null;
};

// 监听弹框状态，当弹框打开时隐藏tooltip
watch(dialogVisible, (isVisible) => {
  if (isVisible) {
    hideTooltip();
  }
});
</script>

<style lang="scss" scoped>
.video-map-container {
  height: 100%;
  display: flex;
  background: #f5f7fa;
  gap: 16px;
  padding: 16px;
}

.left-panel {
  width: 280px;
  min-width: 300px;
  height: 100%;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.right-panel {
  flex: 1;
  height: 100%;
  display: flex;
  flex-direction: column;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  transition: all 0.3s ease;
}

.right-panel.fullscreen-mode {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 9999;
  border-radius: 0;
  box-shadow: none;
}

.electronic-map-view {
  width: 100%;
  height: 100%;
  position: relative;
}

.cesium-container {
  width: 100%;
  height: 100%;
}

.fullscreen-controls {
  position: absolute;
  bottom: 20px;
  right: 20px;
  z-index: 1000;
}

.fullscreen-btn {
  background: rgba(255, 255, 255, 0.9);
  border: 1px solid rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  transition: all 0.3s ease;
  width: 48px;
  height: 48px;
  border-radius: 50%;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0;
  margin: 0;
  outline: none;
}

.fullscreen-btn:hover {
  background: rgba(255, 255, 255, 1);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.2);
  transform: translateY(-2px);
}

.fullscreen-btn:active {
  transform: translateY(0);
}

.fullscreen-icon {
  width: 20px;
  height: 20px;
  color: #606266;
  display: block;
}

.marker-tooltip {
  position: fixed;
  z-index: 10000;
  pointer-events: none;
  background: rgba(0, 0, 0, 0.8);
  color: white;
  padding: 8px 12px;
  border-radius: 6px;
  font-size: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.1);
  max-width: 200px;
}

.tooltip-content {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.tooltip-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.tooltip-label {
  color: #a0a0a0;
  font-weight: 500;
  min-width: 40px;
}

.tooltip-value {
  color: #ffffff;
  font-weight: 400;
  word-break: break-all;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .left-panel {
    width: 300px;
    min-width: 280px;
  }
}

@media (max-width: 768px) {
  .video-map-container {
    flex-direction: column;
    height: auto;
    min-height: 100vh;
  }
  
  .left-panel {
    width: 100%;
    height: 300px;
    min-width: auto;
  }
  
  .right-panel {
    height: calc(100vh - 332px);
  }
}
</style>